package com.intro.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.persistence.Entity;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@Entity
public class MaterialAction extends ActionSupport {
	private File fileMaterial;// Ajax获取图片文件,与控件type=File中的name属性一样
	private String fileMaterialFileName;// Ajax获取图片文件名称,相应的name属性名称+FileName
	private static final int BUFFER_SIZE = 16 * 1024;

	
	
	public File getFileMaterial() {
		return fileMaterial;
	}

	public void setFileMaterial(File fileMaterial) {
		this.fileMaterial = fileMaterial;
	}

	public String getFileMaterialFileName() {
		return fileMaterialFileName;
	}

	public void setFileMaterialFileName(String fileMaterialFileName) {
		this.fileMaterialFileName = fileMaterialFileName;
	}

	/**
	 * 通过Ajax获取图片信息
	 * 
	 * @return
	 * @throws IOException
	 */
	public String ajaxGetImage() throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		if (fileMaterial != null) {
			String fileName = UUID.randomUUID() + "." + fileMaterialFileName;
			String savePath = ServletActionContext.getServletContext()
					.getRealPath("uploadFiles")
					+ "/images/" + fileName;
			System.out.println(savePath);
			copy(fileMaterial, new File(savePath));
			// ImageZipUtil.zipWidthHeightImageFile(fileMaterial, new
			// File(savePath), 40, 40, 1.0f);//压缩图片上传的公共类
			String imgUrl = "uploadFiles/images/" + fileName;
			response.getWriter().print("图片#" + imgUrl + "#上传成功!");// 把相应的地址放到前台解析，通过#符号分割
		} else {
			response.getWriter().print("图片上传失败!");
		}
		return null;
	}

	private String getWebPath() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
		+ request.getServerName() + ":" + request.getServerPort()
		+ path + "/";
		return basePath;

	}

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}